#include "../include/core/config.h"
#include "../include/public/cJSON.h"
#include "../include/public/util.h"
#include "port.h"
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>

/**
 * Name:    el_csv
 * Brief:   解析设备模板,挂载到测点链表
 *          设备模板表头: "id,group,data_name,unit,reg_add,reg_type,endian,dcm,k,fun_num,calc,style,"
 * Input:
 *  @fp:    文件路径
 *  @su:    cfg_su_t*
 * Output:  成功:0 , 失败:-1
 */
static int el_csv(FILE *fp, cfg_su_t *su)
{

    cfg_temp_t *new_temp = NULL;
    new_temp = (cfg_temp_t *)malloc(sizeof(cfg_temp_t));
    new_temp->name = awt_string_duplicate(su->temp_name);
    new_temp->node_list = NULL;
    new_temp->next = NULL;

    char buffer[500] = "";

    /* 跳过表头 */
    fgets(buffer, sizeof(buffer), fp);

    while (fgets(buffer, sizeof(buffer), fp) != NULL)
    {
        char *cols[13];
        if (UTIL_SPLIT(buffer, ',', cols) != 13)
        {
            LOG_E("cfg", "split buf %s len != 13", buffer);
            continue;
        }

        cfg_node_t *node = (cfg_node_t *)malloc(sizeof(cfg_node_t));

        node->id = atoi(cols[0]);
        node->group = atoi(cols[1]);
        node->data_name = awt_string_duplicate(cols[2]);
        node->unit = awt_string_duplicate(cols[3]);

        char *reg_addr = cols[4];
        if (strlen(reg_addr) > 2 && reg_addr[1] == 'x')
        {
            sscanf(reg_addr + 2, "%x", &node->reg_add);
        }
        else if (strlen(reg_addr) > 2 && reg_addr[1] == 'X')
        {
            sscanf(reg_addr + 2, "%x", &node->reg_add);
        }
        else
        {
            node->reg_add = atoi(reg_addr);
        }

        node->reg_type = atoi(cols[5]);
        node->endian = atoi(cols[6]);
        node->dcm = atoi(cols[7]);
        node->k = atoi(cols[8]);
        node->fun_num = atoi(cols[9]);
        node->calc = awt_string_duplicate(cols[10]);
        node->style = atoi(cols[11]);

        new_temp->node_list = util_cfg_node_add(new_temp->node_list, node);
    }

    su->template = new_temp;
    g_cfg->g_template = util_cfg_temp_add(g_cfg->g_template, new_temp);

    return 0;
}

/**
 * Name:    el_parsing
 * Brief:   打开子设备的设备模板
 * Input:
 *  @fp:    文件路径
 *  @su:    子设备节点
 * Output:  成功:0 , 失败:-1
 */
static int el_parsing(const char *path, cfg_su_t *su)
{
    FILE *fp;
    int err = -1;

    fp = fopen(path, "rb");
    if (!fp)
    {
        LOG_E("cfg", "failed to open csv file: %s!\n", path);
        return -1;
    }

    err = el_csv(fp, su);

    fclose(fp);
    return err;
}


/**
 * Name:    cfg_create_root
 * Brief:   生成json文件的root根节点,以防重复打开关闭文件
 * Input:
 *  @json_buf:     json文件路径
 * Output:  cJSON--解析正确,NULL--解析错误
 */
cJSON *cfg_create_root(const char *json_buf)
{
    cJSON *root = cJSON_Parse(json_buf);
    if (root == NULL)
    {
        LOG_E("cfg", "json parsing dtu cfg null\n");
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL)
        {
            LOG_E("cfg", "Error before: %s\n", error_ptr);
        }
        return NULL;
    }

    return root;
}

/**
 * Name:    cfg_create_basic
 * Brief:   解析系统配置文件(SYS.json)中的基础配置
 * Input:
 *  @root:  配置文件根节点
 * Output:  cfg_basic_t*
 */
cfg_basic_t *cfg_create_basic(cJSON *root)
{
    cJSON *head_info = cJSON_GetObjectItem(root, "headInfo");
    if (head_info == NULL)
    {
        LOG_E("cfg", "parsing SYS.headInfo NULL!\n");
        return NULL;
    }
    cJSON *proj_name = cJSON_GetObjectItem(head_info, "projectName");
    if (proj_name == NULL)
    {
        LOG_E("cfg", "parsing SYS.headInfo.projectName NULL!\n");
        return NULL;
    }

    cJSON *basic = cJSON_GetObjectItem(root, "basic");
    if (basic == NULL)
    {
        LOG_E("cfg", "parsing SYS.basic NULL!\n");
        return NULL;
    }

    cJSON *product = cJSON_GetObjectItem(basic, "product");
    if (product == NULL)
    {
        LOG_E("cfg", "parsing SYS.basic.product NULL!\n");
        return NULL;
    }
    cJSON *gw_name = cJSON_GetObjectItem(basic, "name");
    if (gw_name == NULL)
    {
        LOG_E("cfg", "parsing SYS.basic.gw_name NULL!\n");
        return NULL;
    }

    cfg_basic_t *sys = (cfg_basic_t *)malloc(sizeof(cfg_basic_t));
    sys->product = awt_string_duplicate(product->valuestring);
    sys->gw_name = awt_string_duplicate(gw_name->valuestring);
    sys->proj_name = awt_string_duplicate(proj_name->valuestring);

    sys->serial_no = awt_string_duplicate("02220101500026");

    cJSON *eth1 = cJSON_GetObjectItem(root, "eth1");
    if (eth1 == NULL)
    {
        LOG_E("cfg", "parsing SYS.eth1 NULL!\n");
        return NULL;
    }
    cJSON *gw_ip = cJSON_GetObjectItem(eth1, "ip");
    if (gw_ip == NULL)
    {
        LOG_E("cfg", "parsing SYS.eth1.ip NULL!\n");
        return NULL;
    }
    cJSON *gw_mask = cJSON_GetObjectItem(eth1, "mask");
    if (gw_mask == NULL)
    {
        LOG_E("cfg", "parsing SYS.eth1.mask NULL!\n");
        return NULL;
    }
    cJSON *gw_gateway = cJSON_GetObjectItem(eth1, "gateway");
    if (gw_mask == NULL)
    {
        LOG_E("cfg", "parsing SYS.eth1.gwteway NULL!\n");
        return NULL;
    }
    cJSON *gw_dhcp = cJSON_GetObjectItem(eth1, "dhcp");
    if (gw_dhcp == NULL)
    {
        LOG_E("cfg", "parsing SYS.eth1.dhcp NULL!\n");
        return NULL;
    }

    sys->ip = awt_string_duplicate(gw_ip->valuestring);
    sys->mask = awt_string_duplicate(gw_ip->valuestring);
    sys->gateway = awt_string_duplicate(gw_gateway->valuestring);
    sys->dhcp = gw_dhcp->valueint;

    return sys;
}

/**
 * Name:    cfg_create_coll_node
 * Brief:   解析采集配置
 * Input:
 *  @root_sys:  系统配置文件根节点
 *  @root_clt:  工程配置文件根节点
 * Output:  采集链表
 */
cfg_pu_t *cfg_create_coll_node(cJSON *root_sys, cJSON *root_clt)
{
    cJSON *element = NULL;
    cfg_pu_t *coll_header = NULL;

    /* 遍历工程配置(CLT.json)中第一层中采集节点 */

    cJSON_ArrayForEach(element, root_clt)
    {
        const char *key = element->string;
        cJSON *value = element;

        if ((0 == strncmp(key, "trans", 5)) || (0 == strcmp(key, "headInfo")))
        {
            continue;
        }

        cJSON *port_clt = cJSON_GetObjectItem(root_clt, key);
        if (port_clt == NULL)
        {
            continue;
        }

        cJSON *port_sys = cJSON_GetObjectItem(root_sys, key);
        if (port_sys == NULL)
        {
            LOG_E("cfg", "Failed to GetObjectItem %s!", key);
            return coll_header;
        }

        cJSON *port_en = cJSON_GetObjectItem(port_clt, "on_off");
        if (port_en == NULL)
        {
            LOG_E("cfg", "Failed to GetObjectItem %s.on_off!", key);
            return coll_header;
        }
        cJSON *port_proto = cJSON_GetObjectItem(port_clt, "proto");
        if (port_proto == NULL)
        {
            LOG_E("cfg", "Failed to GetObjectItem %s.proto!", key);
            return coll_header;
        }

        cfg_pu_t *new_coll = (cfg_pu_t *)malloc(sizeof(cfg_pu_t));
        memset(new_coll, 0, sizeof(cfg_pu_t));

        if ((0 == strncmp(key, "rs485_", 6)) && (6 < strlen(key)))
        {
            // rs485_1 : id(0)
            // rs485_2 : id(1)
            // ...
            new_coll->id = key[6] - '1';
        }
        else if (0 == strcmp(key, "eth1"))
            new_coll->id = 11;
        else
            new_coll->id = 0xFF;

        new_coll->type = 0; // 采集通道
        new_coll->pkg_send = 0;
        new_coll->pkg_recv = 0;
        new_coll->name = awt_string_duplicate(key);
        new_coll->enable = port_en->valueint;
        new_coll->protoname = awt_string_duplicate(port_proto->valuestring);

        cfg_proto_coll_t *proto_collect = (cfg_proto_coll_t *)malloc(sizeof(cfg_proto_coll_t));
        cJSON *port_gapTimer = cJSON_GetObjectItem(port_clt, "gapTimer");
        if (port_gapTimer == NULL)
        {
            LOG_E("cfg", "Failed to cJSON_GetObjectItem %s.gapTimer!", key);
            return coll_header;
        }
        proto_collect->gapTime = port_gapTimer->valueint;

        cJSON *port_waitTimer = cJSON_GetObjectItem(port_clt, "waitTimer");
        if (port_waitTimer == NULL)
        {
            LOG_E("cfg", "Failed to cJSON_GetObjectItem %s.waitTimer!", key);
            return coll_header;
        }
        proto_collect->waitTimer = port_waitTimer->valueint;

        // eth1
        cJSON *coll_IP = cJSON_GetObjectItem(port_clt, "IP");
        if (coll_IP != NULL)
        {
            proto_collect->IP = awt_string_duplicate(coll_IP->valuestring);
        }
        cJSON *coll_port = cJSON_GetObjectItem(port_clt, "Port");
        if (coll_port != NULL)
        {
            proto_collect->Port = awt_string_duplicate(coll_port->valuestring);
        }

        new_coll->proto_coll = proto_collect;

        // 按照不同的端口号解析程序
        // RS485

        // eth1

        // others

        if (0 == strncmp(key, "rs485_", 6))
        {
            cJSON *baudrate = cJSON_GetObjectItem(port_sys, "baud");
            if (baudrate == NULL)
            {
                LOG_E("cfg", "parsing %s.baudrate NULL!", key);
                return coll_header;
            }
            cJSON *dataBits = cJSON_GetObjectItem(port_sys, "dataBits");
            if (dataBits == NULL)
            {
                LOG_E("cfg", "parsing %s.dataBits NULL!", key);
                return coll_header;
            }
            cJSON *parity = cJSON_GetObjectItem(port_sys, "pority");
            if (parity == NULL)
            {
                LOG_E("cfg", "parsing %s.parity NULL!", key);
                return coll_header;
            }
            cJSON *stop = cJSON_GetObjectItem(port_sys, "stop");
            if (stop == NULL)
            {
                LOG_E("cfg", "parsing %s.stop NULL!", key);
                return coll_header;
            }

            cfg_serial_t *serial = (cfg_serial_t *)malloc(sizeof(cfg_serial_t));
            memset(serial, 0, sizeof(cfg_serial_t));

            /*
                "dataBits": 8,
                "pority": 0,  // 0-None; 1-odd (奇); 2-enen
                "stop": 1
            */
            char baud_buff[10] = {'9', '6', '0', '0'};
            char format_buff[10] = {'N', '8', '1'};
            int parity_bit = parity->valueint;
            switch (parity_bit)
            {
            case 1:
                format_buff[0] = 'O';
                break;
            case 2:
                format_buff[0] = 'E';
                break;
            default:
                break;
            }
            format_buff[1] = dataBits->valueint + '0';
            format_buff[2] = stop->valueint + '0';

            sprintf(baud_buff, "%d", baudrate->valueint);

            serial->format = awt_string_duplicate(format_buff);
            serial->baudrate = awt_string_duplicate(baud_buff);
            new_coll->port.setting = (void *)serial;
        }
        else if (0 == strcmp(key, "eth1"))
        {
            // TODO: cfg_enet_t
        }
        new_coll->port.type = awt_string_duplicate(key);

        // devs
        cJSON *devs = cJSON_GetObjectItem(port_clt, "devList");
        if (devs == NULL)
        {
            LOG_E("cfg", "parsing CLT.%s.devList NULL!", key);
            return coll_header;
        }

        new_coll->devsumlist = cJSON_GetArraySize(devs);

        // 新增节点
        coll_header = util_cfg_pu_add(coll_header, new_coll);

        cJSON *dev = NULL;
        cJSON_ArrayForEach(dev, devs)
        {
            cJSON *su_id = cJSON_GetObjectItem(dev, "devId");
            if (su_id == NULL)
            {
                LOG_E("cfg", "parsing %s.devList.devid NULL!", key);
                return coll_header;
            }
            cJSON *su_name = cJSON_GetObjectItem(dev, "devName");
            if (su_name == NULL)
            {
                LOG_E("cfg", "parsing %s.devList.devName NULL!", key);
                return coll_header;
            }
            cJSON *su_addr = cJSON_GetObjectItem(dev, "addr");
            if (su_addr == NULL)
            {
                LOG_E("cfg", "parsing %s.devList.addr NULL!", key);
                return coll_header;
            }
            cJSON *su_temp = cJSON_GetObjectItem(dev, "dev_template");
            if (su_temp == NULL)
            {
                LOG_E("cfg", "parsing %s.devList.dev_template NULL!", key);
                return coll_header;
            }

            cJSON *su_loop = cJSON_GetObjectItem(dev, "loops");
            if (su_loop == NULL)
            {
                LOG_E("cfg", "parsing %s.devList.loop NULL!", key);
                return coll_header;
            }
            cfg_su_t *su = (cfg_su_t *)malloc(sizeof(cfg_su_t));
            memset(su, 0, sizeof(cfg_su_t));
            su->id = su_id->valueint;
            su->name = awt_string_duplicate(su_name->valuestring);
            su->temp_name = awt_string_duplicate(su_temp->valuestring);
            su->template = NULL;
            su->ch = NULL;
            su->subdev_list = NULL;
            su->addr = su_addr->valueint;
            su->loop = su_loop->valueint;
            su->state = 0;

            // 创建模板库

            // 模板不存在 -->> free(su) --->> continue

            char path[100] = "";
            sprintf(path, "./cfg/template/south/%s", su->temp_name);
            printf("----------->> %s\n",path);

            uint8_t temp_flag = 0;
            cfg_temp_t *template = g_cfg->g_template;
            while (template)
            {
                if (0 == strcmp(template->name, su->temp_name))
                {
                    temp_flag = 1;
                    su->template = template;
                }
                template = template->next;
            }

            if(0 == temp_flag)
            {
                // 创建新模板 加入到模板库链表
                int err = el_parsing(path,su);
                if (err < 0)
                {
                    LOG_E("cfg", "parsing el:%s error!\n", path);
                    free(su);
                    continue;
                }
            }

            // judge loops 回路数
            
            int cnts = 0;   // su / subdev 的测点
            if(su->loop <= 1)
            {
                //  获取测点数量
                cnts = util_get_ch_cnts(su,1);
                su->ch = (cfg_ch_t *)malloc(cnts* sizeof(cfg_ch_t));
                su->valcntsum = cnts;
                util_ch_init(su->template, su->ch, 1);
            }
            else
            {
                int i;
                for(i=0;i<su->loop;i++)
                {
                    cnts = util_get_ch_cnts(su,i);
                    cfg_subdev_t *subdev = (cfg_subdev_t *)malloc(sizeof(cfg_subdev_t));
                    subdev->ch = NULL;
                    subdev->group_id = i;
                    subdev->ch = (cfg_ch_t *)malloc(cnts* sizeof(cfg_ch_t));
                    subdev->valcntsum = cnts;
                    util_ch_init(su->template, subdev->ch, i);
                }
            }

            cfg_pu_t *cur = coll_header;
            while (cur->next)
                cur = cur->next;
            cur->su = util_cfg_su_add(cur->su, su);
        }
    }
    return coll_header;
}

/**
 * Name:    cfg_create_trans_node
 * Brief:   解析转发配置
 * Input:
 *  @root_sys:  系统配置文件根节点
 *  @root_clt:  工程配置文件根节点
 * Output:  转发链表
 */
cfg_pu_t *cfg_create_trans_node(cJSON *root_sys, cJSON *root_clt)
{
    int index = 0;
    cfg_pu_t *trans_header = NULL;
    cJSON *element = NULL;

    /* 遍历工程配置(CLT.json)中第一层中以 trans 开头的JSON节点 */

    cJSON_ArrayForEach(element, root_clt)
    {
        const char *key = element->string;
        cJSON *value = element;

        if (0 != strncmp(key, "trans", 5))
        {
            continue;
        }

        cJSON *puenable = cJSON_GetObjectItem(value, "on_off");
        if (puenable == NULL)
        {
            LOG_E("cfg", "parsing CLT.%s.on_off NULL\n", key);
            return NULL;
        }
        cJSON *puname = cJSON_GetObjectItem(value, "port");
        if (puname == NULL)
        {
            LOG_E("cfg", "parsing CLT.%s.port NULL\n", key);
            return NULL;
        }
        cJSON *protoname = cJSON_GetObjectItem(value, "proto");
        if (protoname == NULL)
        {
            LOG_E("cfg", "parsing CLT.%s.proto NULL\n", key);
            return NULL;
        }
        cJSON *parlist = cJSON_GetObjectItem(value, "parlist");
        if (parlist == NULL)
        {
            LOG_E("cfg", "parsing CLT.%s.parlist NULL\n", key);
            return NULL;
        }

        cfg_pu_t *new_trans = (cfg_pu_t *)malloc(sizeof(cfg_pu_t));
        memset(new_trans, 0, sizeof(cfg_pu_t));
        new_trans->type = 1; // 转发通道
        new_trans->id = index++;
        new_trans->pkg_send = 0;
        new_trans->pkg_recv = 0;
        new_trans->name = awt_string_duplicate(key);
        new_trans->port.type = awt_string_duplicate(puname->valuestring);
        new_trans->protoname = awt_string_duplicate(protoname->valuestring);
        new_trans->proto_coll = NULL;
        new_trans->enable = puenable->valueint;
        new_trans->hanlder.rbroot = NULL;
        new_trans->hanlder.cjson = cJSON_Duplicate(parlist, 1);
        new_trans->su = NULL;

        // 新增节点
        trans_header = util_cfg_pu_add(trans_header, new_trans);
    }

    /* 默认添加对接本地调试上位机的trans节点 */
    {
        cfg_pu_t *swj_pu = (cfg_pu_t *)malloc(sizeof(cfg_pu_t));
        memset(swj_pu, 0, sizeof(cfg_pu_t));
        swj_pu->name = awt_string_duplicate("trans0");
        swj_pu->port.type = awt_string_duplicate("eth1"); // FIXME: 支持TCP和RS485 两种通讯方式
        swj_pu->protoname = awt_string_duplicate("AWT-IOT");
        swj_pu->enable = 1;
        swj_pu->hanlder.rbroot = NULL;
        swj_pu->hanlder.cjson = NULL;

        // 新增节点
        trans_header = util_cfg_pu_add(trans_header, swj_pu);
    }

    return trans_header;
}


/*
static int api_alm_init(int devid, char *alm_name, cfg_alm_t *alm)
{
    // find su & ch
    cfg_pu_t *pu = g_cfg->g_coll_link;
    while (pu)
    {
        cfg_su_t *su = pu->su;
        while (su)
        {
            if (su->id == devid)
            {
                cfg_ch_t *ch = su->ch;
                while (ch)
                {
                    cfg_node_t *node_header = su->temp->node;
                    cfg_node_t *node = node_header + ch->id - 1;
                    if (0 == strcmp(node->data_name, alm_name))
                    {
                        ch->alm = alm;
                        return 0;
                    }
                    ch = ch->next;
                }
            }
            su = su->next;
        }
        pu = pu->next;
    }
    return -1;
}



*/


/**
 * Name:    cfg_create_alarm
 * Brief:   解析告警配置
 * Input:
 *  @root_rule:  告警配置文件根节点
 * Output:  0:SUCCESS -1: ERROR
 */


// int cfg_create_alarm(cJSON *root_rule)
// {
//     // ALM_YC
//     // ALM_YX

//     cJSON *cJSON_ALM_YC = cJSON_GetObjectItem(root_rule,"ALM_YC");
//     cJSON *cJSON_ALM_YX = cJSON_GetObjectItem(root_rule,"ALM_YX");
//     if(cJSON_ALM_YC == NULL || cJSON_ALM_YX == NULL)
//     {
//         return ;
//     }

//     cJSON *element_yx = NULL;
//     cJSON *element_yc = NULL;

//     /* 遍历工程配置(RULE.json)中第一层中 ALM_YX JSON节点 */
//     /*
//         {
//             "DevID": [1,2],
//             "MPID": "YX1",
//             "AlmEnab": 1,
//             "AlarmDelay": 100,
//             "NormalVal": 0,			// 正常状态 0 1 2(固定不变)
//             "AlarmPR": 0
//         },
//     */
//     cJSON_ArrayForEach(element_yx, cJSON_ALM_YX)
//     {
//         cJSON *alm_enab = cJSON_GetObjectItem(element_yx,"AlmEnab");
//         if(alm_enab == NULL) return -1;

//         if(alm_enab->valueint == 0) continue;

//         cJSON *DevID_Set = cJSON_GetObjectItem(element_yx,"DevID");
//         if(DevID_Set == NULL) return -1;
//         int set_cnt = cJSON_GetArraySize(DevID_Set);
//         if(set_cnt == 0) continue;

//         cJSON * MP = cJSON_GetObjectItem(element_yx,"MPID");
//         if(MP == NULL) return -1;
//         char *alm_name = MP->valuestring;

//         cJSON *NormalVal = cJSON_GetObjectItem(element_yx,"NormalVal");
//         if(NormalVal == NULL) return -1;
//         uint8_t nor_val = NormalVal->valueint;

//         cfg_alm_yx_t *alm_yx = (cfg_alm_yx_t *)malloc(sizeof(cfg_alm_yx_t));
//         alm_yx->normal_val = nor_val;

//         cfg_alm_t *alm = (cfg_alm_t *)malloc(sizeof(cfg_alm_t));
//         alm->alm_type = 1;
//         alm->content = (void *)alm_yx;

//         int i;
//         for(i=0;i<set_cnt;i++)
//         {
//             cJSON *Device = cJSON_GetArrayItem(DevID_Set,i);
//             int devid = Device->valueint;

//             api_alm_init(devid,alm_name,alm);
//         }
//     }

//     /* 遍历工程配置(RULE.json)中第一层中 ALM_YC JSON节点 */
//     /*
//         {	
//             "DevID": [1,2,3,4],		// 设备id集合（设备模板相同）
//             "MP": "Ua",				// 测点id
//             "AlmEnab": 1,			// 报警开关
//             "AlarmDelay": 100,		// 延时时间（毫秒）
//             "DeadBand": 3,			// 死区
//             "LL":{					// 低低限
//                 "LLEnab": 1,		// 低低限开关
//                 "LLValue": 0,		// 报警值
//                 "LLPR": 0			// 优先级 （低级告警，高级报警，紧急告警）
//             },	
//             "LO":{					// 低限
//                 "LOEnab": 1,	
//                 "LOValue":30,
//                 "LOPR": 0
//             },
//             "HI":{					// 高限
//                 "HIEnab": 1,		
//                 "HIValue": 60,		
//                 "HIPR": 0
//             },
//             "HH":{					// 高高限
//                 "HHEnab": 1,
//                 "HHValue": 0,
//                 "HHPR": 0
//             },
//             "DEV":{					// 偏差
//                 "DEVEnab": 1,
//                 "DEVValue": 20,
//                 "DEVPR": 0,
//                 "DEVSet": 100		// 设定值
//             },
//             "RATE":{				// 变化率
//                 "RATEEnab": 1,
//                 "RATEValue": 20,
//                 "RATEPR": 0,
//                 "RATECYC": 10		// 周期	（秒）
//             }
//         }
//     */
//     cJSON_ArrayForEach(element_yc, cJSON_ALM_YC)
//     {
//         cJSON *alm_enab = cJSON_GetObjectItem(element_yc,"AlmEnab");
//         if(alm_enab == NULL) return -1;

//         if(alm_enab->valueint == 0) continue;

//         cJSON *DevID_Set = cJSON_GetObjectItem(element_yc,"DevID");
//         if(DevID_Set == NULL) return -1;
//         int set_cnt = cJSON_GetArraySize(DevID_Set);
//         if(set_cnt == 0) continue;

//         cJSON * MP = cJSON_GetObjectItem(element_yc,"MPID");
//         if(MP == NULL) return -1;
//         char *alm_name = MP->valuestring;

//         cJSON * dead_band = cJSON_GetObjectItem(element_yc,"DeadBand");
//         if(dead_band == NULL) return -1;

//         cJSON * ll = cJSON_GetObjectItem(element_yc,"LL");
//         cJSON * lo = cJSON_GetObjectItem(element_yc,"LO");
//         cJSON * hi = cJSON_GetObjectItem(element_yc,"HI");
//         cJSON * hh = cJSON_GetObjectItem(element_yc,"HH");
//         cJSON * dev = cJSON_GetObjectItem(element_yc,"DEV");
//         cJSON * rate = cJSON_GetObjectItem(element_yc,"RATE");

//         if(ll == NULL || lo == NULL || hi == NULL || hh == NULL || dev == NULL || rate == NULL)
//         {
//             return -1;
//         }

//         cJSON * llen = cJSON_GetObjectItem(ll,"LLEnab");
//         cJSON * llvalue = cJSON_GetObjectItem(ll,"LLValue");
//         if(llen == NULL || llvalue == NULL) return -1;

//         cJSON * loen = cJSON_GetObjectItem(lo,"LOEnab");
//         cJSON * lovalue = cJSON_GetObjectItem(lo,"LOValue");
//         if(loen == NULL || lovalue == NULL) return -1;

//         cJSON * hien = cJSON_GetObjectItem(hi,"HIEnab");
//         cJSON * hivalue = cJSON_GetObjectItem(hi,"HIValue");
//         if(hien == NULL || hivalue == NULL) return -1;

//         cJSON * hhen = cJSON_GetObjectItem(hh,"LOEnab");
//         cJSON * hhvalue = cJSON_GetObjectItem(hh,"LOValue");
//         if(hhen == NULL || hhvalue == NULL) return -1;

//         cJSON * deven = cJSON_GetObjectItem(dev,"DEVEnab");
//         cJSON * devvalue = cJSON_GetObjectItem(dev,"DEVValue");
//         cJSON * devset = cJSON_GetObjectItem(dev,"DEVSet");
//         if(deven == NULL || devvalue == NULL || devset == NULL) return -1;

//         cJSON * rateen = cJSON_GetObjectItem(rate,"RATEEnab");
//         cJSON * ratevalue = cJSON_GetObjectItem(rate,"RATEValue");
//         cJSON * ratecyc = cJSON_GetObjectItem(rate,"RATECYC");
//         if(rateen == NULL || ratevalue == NULL || ratecyc == NULL) return -1;

//         cfg_alm_yc_t *alm_yc = (cfg_alm_yc_t *)malloc(sizeof(cfg_alm_yc_t));
//         alm_yc->dead_band = dead_band->valueint;
        
//         alm_yc->LL_en = llen->valueint;
//         alm_yc->LL_val = llvalue->valueint;

//         alm_yc->LO_en = loen->valueint;
//         alm_yc->LO_val = lovalue->valueint;

//         alm_yc->HI_en = hien->valueint;
//         alm_yc->HI_val = hivalue->valueint;

//         alm_yc->HH_en = hhen->valueint;
//         alm_yc->HH_val = hhvalue->valueint;

//         alm_yc->DEV_en = deven->valueint;
//         alm_yc->DEV_val = devvalue->valueint;
//         alm_yc->DEV_set = devset->valueint;

//         alm_yc->RATE_en = rateen->valueint;
//         alm_yc->RATE_val = ratevalue->valueint;
//         alm_yc->RATE_cyc = ratecyc->valueint;

//         cfg_alm_t *alm = (cfg_alm_t *)malloc(sizeof(cfg_alm_t));
//         alm->alm_type = 0;
//         alm->content = (void *)alm_yc;

//         int i;
//         for(i=0;i<set_cnt;i++)
//         {
//             cJSON *Device = cJSON_GetArrayItem(DevID_Set,i);
//             int devid = Device->valueint;

//             api_alm_init(devid,alm_name,alm);
//         }
//     }

//     return 0;
// }

